package com.newenergy.wisehome.ui.fragment;


import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.newenergy.wisehome.R;
import com.newenergy.wisehome.common.helper.LogHelper;
import com.newenergy.wisehome.common.helper.SPUtil;
import com.newenergy.wisehome.common.helper.SpaceItemDecoration;
import com.newenergy.wisehome.common.util.LocaleUtil;
import com.newenergy.wisehome.config.AppManager;
import com.newenergy.wisehome.config.Constants;
import com.newenergy.wisehome.data.bean.BallLight;
import com.newenergy.wisehome.data.bean.DeviceCategory;
import com.newenergy.wisehome.data.bean.Scene;
import com.newenergy.wisehome.data.ormlite.dao.BallLightDao;
import com.newenergy.wisehome.ui.adapter.IconAdapter;
import com.newenergy.wisehome.ui.adapter.SceneModeAdapter;
import com.newenergy.wisehome.ui.widget.ColorPickerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 球泡灯操作页面
 */
public class GroupFragment extends BaseFragment implements SeekBar
        .OnSeekBarChangeListener, RecyclerArrayAdapter.OnItemClickListener {

    private static final String ARG_DEVICECATEGORY = "arg_devicecategory";
    private static final String ARG_BALLLIGHT = "arg_balllight";

    private static final int HANDLE_CAN_ADVERTISE = 0x11;
    @BindView(R.id.btn_back)
    Button mBtnBack;
    @BindView(R.id.tv_back)
    TextView mTvBack;
    @BindView(R.id.tv_page)
    TextView mTvPage;
    @BindView(R.id.btn_add)
    Button mBtnAdd;
    @BindView(R.id.btn_help)
    Button mBtnHelp;
    @BindView(R.id.btn_collect)
    Button mBtnCollect;
    @BindView(R.id.colorPicker)
    ColorPickerView mColorPicker;

    @BindView(R.id.seekbar_ld)
    SeekBar mSeekbarLd1;
    @BindView(R.id.rl_color_picker)
    RelativeLayout mRlColorPicker;

    @BindView(R.id.rl_two_seekbar)
    RelativeLayout mRlTwoSeekbar;
    @BindView(R.id.seekbar_ld2)
    SeekBar mSeekbarLd2;
    @BindView(R.id.seekbar_color)
    SeekBar mSeekbarColor;

    @BindView(R.id.rlv_scene)
    EasyRecyclerView mRlvScene;


    protected DeviceCategory mDeviceCategory;
    protected BallLight mGroup;
    //    private static boolean canAdvertise = true;
//    private boolean isResume = true;
    private EasyRecyclerView mIconRecyclerView;
    private IconAdapter mIconAdapter;
    private SceneModeAdapter mSceneModeAdapter;


    private View mRootView;
    private List<Scene> mSWSceneList;
    private List<Scene> mRGBSceneList;
    public int mSceneIndex;
    private Scene mScene;
    private long mCurrTime = 0;
    private int confirmType = 1;

    private boolean isOnResume = true;
    private boolean isControlScene;


    /*色盘*/
    public GroupFragment() {
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_group;
    }


    @Override
    public void init(View rootView) {
        mRootView = rootView;
        initSceneRecyclerView(getContext().getApplicationContext());

    }

    private void initData() {
        initScene();
        initSW();
        initColorDiskListener();
        mGroup.setMode(2);
        AppManager.getInstance(getContext()).mDefaultBallLight.setMode(2);
        BallLightDao ballLightDao = new BallLightDao(getContext());
        ballLightDao.updateBallLight(mGroup);
    }

    @Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
    }

    private void initSceneRecyclerView(Context context) {
        mRlvScene.setLayoutManager(new GridLayoutManager(context, 4));
        mSceneModeAdapter = new SceneModeAdapter(context);
        mRlvScene.addItemDecoration(new SpaceItemDecoration(dpToPx(11)));
        mRlvScene.setAdapter(mSceneModeAdapter);
        mSceneModeAdapter.setOnItemClickListener(this);

    }

    @Override
    public void onStop() {
        super.onStop();
//        isResume = true;
    }

    /**
     * 获取色盘的RGB
     *
     * @param red
     * @param blue
     * @param green
     */
    private void colorChanged(int red, int blue, int green) {
        LogHelper.i("notifyColorChanged  red=" + red + "  blue=" + blue + "green=" + green /*+ " canAdvertise=" + canAdvertise*/);

        boolean b = checkAdvertisIntval();
        if (b) {
            String rgbHex = new StringBuilder().append(numToHex(red)).append(numToHex(green)).append(numToHex(blue)).toString();
            mGroup.setRgb(rgbHex);
            AppManager.getInstance(mainActivity).controlSeekBarRGB(mGroup, "00");

           /* if (mGroup.getFamilyId().equals("12345678")) {
                AppManager.getInstance(getContext()).mDefaultBallLight.setRgb(rgbHex);
            }*/

        }
    }

    private boolean checkAdvertisIntval() {
        long currentTimeMillis = System.currentTimeMillis();
        long intval = currentTimeMillis - mCurrTime;
        if (intval > 120) {
            mCurrTime = currentTimeMillis;
            return true;
        }
        return false;
    }


    @Override
    public void onResume() {
        super.onResume();
        Log.e("lifecycle", "GroupFragment:onResume");
        if (isOnResume) {
            if (mGroup != null) {
                mColorPicker.setPickerLocation(mGroup.getCenterX(), mGroup.getCenterY());
            }
            if (AppManager.getInstance(getContext()).isControlAll) {
                mGroup = AppManager.getInstance(getContext()).mAllGroup;
                AppManager.getInstance(getContext()).mSelectDeviceCategory = mGroup.covertToDeviceCategory();

            } else {
                mGroup = AppManager.getInstance(getContext()).selectGroup;
//                AppManager.getInstance(getContext()).mSelectDeviceCategory=mGroup.covertToDeviceCategory();
            }

            initData();
            refreshData();
            showView();

            mSeekbarLd1.setMax(235);
            mSeekbarLd2.setMax(235);
            mSeekbarColor.setMax(255);

            mSeekbarLd1.setOnSeekBarChangeListener(this);
            mSeekbarLd2.setOnSeekBarChangeListener(this);
            mSeekbarColor.setOnSeekBarChangeListener(this);


            if (LocaleUtil.getLanguage().startsWith("zh")) {
                mBtnHelp.setBackgroundResource(R.drawable.btn_help_n);
                mBtnHelp.setVisibility(View.VISIBLE);
            } else {
                mBtnHelp.setVisibility(View.GONE);
            }

            if (mGroup.getFamilyId().equals("12345678")) {
                mBtnAdd.setVisibility(View.GONE);

            } else {

                if (mGroup.getGroupId().equals("00")) {
                    mBtnAdd.setVisibility(View.GONE);

                } else {
                    if (AppManager.getInstance(mainActivity).mCurrFamily.getType() != 0) {
                        mBtnAdd.setVisibility(View.VISIBLE);
                        mBtnAdd.setBackgroundResource(R.drawable.btn_add_n);
                    } else {
                        mBtnAdd.setVisibility(View.GONE);
                    }

                }
            }

        }
    }

    /**
     * 初始化色盘状态监听器
     */
    private void initColorDiskListener() {
        mColorPicker.setColorChangedListener(new ColorPickerView.OnColorChangedListener() {

            @Override
            public void startDown() {
                if (mScene != null && mSceneModeAdapter != null) {
                    mScene.setChecked(false);
                    mSceneModeAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void notifyColorChanged(int red, int blue, int
                    green) {
                AppManager.getInstance(getContext()).isStopTouch = false;
                colorChanged(red, blue, green);
            }

            @Override
            public void stopMove() {
                mCurrTime = 0;
                AppManager.getInstance(getContext()).isStopTouch = true;
            }

            @Override
            public void pickerCenterChanged(int centerX, int centerY) {

                LogHelper.i("pickerCenterChanged:centerX=" + centerX + "  centerY=" + centerY);

                mGroup.setCenterX(centerX);
                mGroup.setCenterY(centerY);
                if (mGroup.getFamilyId().equals("12345678")) {
                    AppManager.getInstance(getContext()).mDefaultBallLight = mGroup;
                }

            }
        });
    }

    private void resetSeekBar1Value() {
        mSeekbarLd1.setProgress(mGroup.getLd1());
    }

    private void resetSeekBarValue() {
//        isResume = true;
        mSeekbarLd1.setProgress(mGroup.getLd1());
        mSeekbarLd2.setProgress(mGroup.getLd1());
        mSeekbarColor.setProgress(mGroup.getSw());
//        isResume = false;
    }

    private void showView() {
        if (mGroup == null) {
            return;
        }
        int mode = mGroup.getMode();
        boolean isShowColorDisk = (mode == 1);
        mBtnCollect.setSelected(!isShowColorDisk);
        mRlColorPicker.setVisibility(isShowColorDisk ? View.VISIBLE : View.GONE);
        mRlTwoSeekbar.setVisibility(isShowColorDisk ? View.GONE : View.VISIBLE);
        refreshScene();
        resetSeekBarValue();
    }

    private void refreshData() {
        if (mGroup == null) {
            return;
        }
        mTvPage.setText(mGroup.getName());
        resetSeekBarValue();

    }

    private void refreshScene() {
        int mode = mGroup.getMode();
        if (mode == 1) {
            mSceneModeAdapter.refreshData(mRGBSceneList);
        } else if (mode == 2) {
            mSceneModeAdapter.refreshData(mSWSceneList);
        }
        if (mScene != null) {
            mScene.setChecked(false);
        }
    }


    @OnClick({R.id.btn_back, R.id.tv_back, R.id.btn_collect,
            R.id.btn_add, R.id.btn_help})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                doBack();
                break;
            case R.id.tv_back:
                doBack();
                break;

            case R.id.btn_help://语音命令提示
//                start(SetTimingFragment.newInstance(mGroup));
                showPopupWindow(mBtnHelp, R.drawable.light_speech_help_dialog);

                break;

            case R.id.btn_add://添加设备

                confirmType = 1;
                String msg = getString(R.string.open_before_add);
                showConfirmDialog(msg);
                break;

            case R.id.btn_collect:

                boolean isSelected = !mBtnCollect.isSelected();
                int mode = isSelected ? 2 : 1;


                mGroup.setMode(mode);
                showView();

                if (mode == 1) {
                    AppManager.getInstance(mainActivity).controlRGB(mGroup, "00");
                } else {
                    AppManager.getInstance(mainActivity).controlSW(mGroup, "00");
                }

                if (mGroup.getFamilyId().equals("12345678")) {
                    AppManager.getInstance(getContext()).mDefaultBallLight = mGroup;
                } else {
                    if (mGroup.getGroupId().equals("00")) {
                        AppManager.getInstance(getContext()).mAllGroup = mGroup;
                    } else {
                        BallLightDao ballLightDao = new BallLightDao(getContext());
                        ballLightDao.updateBallLight(mGroup);
                    }

                }

                break;

        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (isControlScene) {
            return;
        }
        AppManager.getInstance(getContext()).isStopTouch = false;
//        if (isResume) return;
        Log.i("QBH", "onProgressChanged：" + progress);

        if (!checkAdvertisIntval()) {
            return;
        }
        switch (seekBar.getId()) {
            case R.id.seekbar_ld:
                setLd1Value();
                AppManager.getInstance(mainActivity).controlSeekBarRGB(mGroup, "00");
                break;

            case R.id.seekbar_ld2:
                setLd2Value();
                AppManager.getInstance(mainActivity).controlSeekBarSW(mGroup, "80");
                break;

            case R.id.seekbar_color:
                setSwValue();
                AppManager.getInstance(mainActivity).controlSeekBarSW(mGroup, "00");
                break;
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        if (mScene != null && mSceneModeAdapter != null) {
            mScene.setChecked(false);
            mSceneModeAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        mCurrTime = 0;
        AppManager.getInstance(getContext()).isStopTouch = true;
//        removeMsg(HANDLE_CAN_ADVERTISE);
//        canAdvertise = true;
        switch (seekBar.getId()) {
            case R.id.seekbar_ld:
                setLd1Value();
                AppManager.getInstance(mainActivity).controlSeekBarRGB(mGroup, "00");
                break;
            case R.id.seekbar_ld2:
                setLd2Value();
                AppManager.getInstance(mainActivity).controlSeekBarSW(mGroup, "80");
                break;
            case R.id.seekbar_color:
                setSwValue();
                AppManager.getInstance(mainActivity).controlSeekBarSW(mGroup, "00");
                break;
        }
    }

    /**
     * 获取亮度百分比
     */
    public void setLd2Value() {
        mGroup.setLd1(mSeekbarLd2.getProgress());
    }

    private void setLd1Value() {
        mGroup.setLd1(mSeekbarLd1.getProgress());
    }

    private void setSwValue() {
        mGroup.setSw(mSeekbarColor.getProgress());
    }

    private void initScene() {
        mRGBSceneList = new ArrayList<>();
        mRGBSceneList.add(new Scene(getString(R.string.scene_sunrise), "rgb_btn_sunrise_selector"));
        mRGBSceneList.add(new Scene(getString(R.string.scene_sunset), "rgb_btn_sunset_selector"));
        mRGBSceneList.add(new Scene(getString(R.string.scene_breathe), "rgb_btn_breathe_selector"));
        mRGBSceneList.add(new Scene(getString(R.string.scene_colorful_gradient), "rgb_btn_change_selector"));
        mRGBSceneList.add(new Scene(getString(R.string.scene_colorful_twinkle), "rgb_btn_twinkle_selector"));
        mRGBSceneList.add(new Scene(getString(R.string.scene_reading), "rgb_btn_read_selector"));
        mRGBSceneList.add(new Scene(getString(R.string.scene_seafront), "rgb_btn_sea_selector"));
        mRGBSceneList.add(new Scene(getString(R.string.scene_candle_light), "rgb_btn_candle_selector"));

        //定时
       /* if (!mGroup.getFamilyId().equals("12345678")) {
            mRGBSceneList.add(new Scene(getString(R.string.btn_timing),"btn_set_timing_selector"));
        }*/

    }


    private void initSW() {
        mSWSceneList = new ArrayList<>();
        mSWSceneList.add(new Scene(getString(R.string.scene_diet), "warm_btn_neutral_selector"));
        mSWSceneList.add(new Scene(getString(R.string.scene_sunlight), "warm_btn_yellow_selector"));
        mSWSceneList.add(new Scene(getString(R.string.scene_white), "warm_btn_white_selector"));
        mSWSceneList.add(new Scene(getString(R.string.scene_night_light), "warm_btn_nightlight_selector"));
        mSWSceneList.add(new Scene(getString(R.string.scene_afternoon), "warm_btn_afternoon_selector"));
        mSWSceneList.add(new Scene(getString(R.string.scene_moonlight), "warm_btn_moon_selector"));
        mSWSceneList.add(new Scene(getString(R.string.scene_auxiliary), "warm_btn_assist_selector"));
        mSWSceneList.add(new Scene(getString(R.string.scene_warm), "warm_btn_change_selector"));

        //定时
       /* if (!mGroup.getFamilyId().equals("12345678")) {
            mSWSceneList.add(new Scene(getString(R.string.btn_timing),"btn_set_timing_selector"));
        }*/


    }


    @Override
    public void onItemClick(int position) {
        //给滑条赋值会触发onProgressChange方法调用，发送两次不同数据
        isControlScene = true;
        List<Scene> allData = mSceneModeAdapter.getAllData();
        if (allData == null || allData.size() <= position) {
            return;
        }//防止数组越界

//        int mode = mGroup.getMode();
//        BallLightDao ballLightDao = new BallLightDao(getContext());
        Scene scene = mSceneModeAdapter.getItem(position);

        String name = scene.getName();
        if (name.equalsIgnoreCase(getString(R.string.scene_sunrise))) {//日出
            mSceneIndex = 0;
            mGroup.setRgb("ffffff");
            mGroup.setMode(1);

            AppManager.getInstance(mainActivity).controlScene(mGroup, "ffffff41", "0affff");
        } else if (name.equalsIgnoreCase(getString(R.string.scene_sunset))) {//日落
            mSceneIndex = 1;
            mGroup.setRgb("ffffff");
            mGroup.setMode(1);
            AppManager.getInstance(mainActivity).controlScene(mGroup, "ffffff41", "ff0aff");
        } else if (name.equalsIgnoreCase(getString(R.string.scene_breathe))) {//"呼吸灯"
            String data1 = mGroup.getRgb() + "81";
            String data2 = "02FF02";
            mSceneIndex = 2;
            mGroup.setMode(1);
            AppManager.getInstance(mainActivity).controlScene(mGroup, data1, data2);
        } else if (name.equalsIgnoreCase(getString(R.string.scene_colorful_gradient))) {//"七彩渐变"
            mSceneIndex = 3;
            mGroup.setMode(1);
            AppManager.getInstance(mainActivity).controlScene(mGroup, "ffffff51", "ffffff");
        } else if (name.equalsIgnoreCase(getString(R.string.scene_colorful_twinkle))) {//"七彩闪烁"
            mSceneIndex = 4;
            mGroup.setMode(1);
            AppManager.getInstance(mainActivity).controlScene(mGroup, "ffffff31", "ff0aff");


        } else if (name.equalsIgnoreCase(getString(R.string.scene_reading))) {//"阅读"
            mSceneIndex = 5;
            mGroup.setRgb("ffffff");
            mGroup.setLd1(118);
            mGroup.setMode(1);
            AppManager.getInstance(mainActivity).controlScene(mGroup, "ffffff01", "7f7fff");


        } else if (name.equalsIgnoreCase(getString(R.string.scene_seafront))) {//"海边"
            mSceneIndex = 6;
            mGroup.setRgb("007fff");
            mGroup.setLd1(235);
            mGroup.setMode(1);
            AppManager.getInstance(mainActivity).controlScene(mGroup, "007fff01", "ffffff");


        } else if (name.equalsIgnoreCase(getString(R.string.scene_candle_light))) {//"烛光"
            mSceneIndex = 7;
            mGroup.setRgb("ff9905");
            mGroup.setLd1(235);
            mGroup.setMode(1);
            AppManager.getInstance(mainActivity).controlScene(mGroup, "ff990501", "ffffff");

        } else if (name.equalsIgnoreCase(getString(R.string.btn_timing))) {//"定时"
            start(SetTimingFragment.newInstance(mGroup));

        } else if (name.equalsIgnoreCase(getString(R.string.scene_diet))) {//"中性光"
            mGroup.setSw(127);
            mGroup.setLd1(235);
            mGroup.setMode(2);
            mSceneIndex = 0;
            AppManager.getInstance(mainActivity).controlScene(mGroup, "7f7f0000", "ffffff");

        } else if (name.equalsIgnoreCase(getString(R.string.scene_sunlight))) {//"黄光"
            mGroup.setSw(255);
            mGroup.setLd1(235);
            mGroup.setMode(2);
            mSceneIndex = 1;
            AppManager.getInstance(mainActivity).controlScene(mGroup, "ff000000", "ffffff");

        } else if (name.equalsIgnoreCase(getString(R.string.scene_white))) {//"白光"
            mGroup.setSw(0);//"纯白改成白光"
            mGroup.setLd1(235);
            mGroup.setMode(2);
            mSceneIndex = 2;
            AppManager.getInstance(mainActivity).controlScene(mGroup, "00ff0000", "ffffff");

        } else if (name.equalsIgnoreCase(getString(R.string.scene_night_light))) {//"小夜灯"
            mGroup.setSw(127);//"小夜灯"
            mGroup.setLd1(0);
            mGroup.setMode(2);
            mSceneIndex = 3;
            AppManager.getInstance(mainActivity).controlScene(mGroup, "7f7f0000", "1414ff");

        } else if (name.equalsIgnoreCase(getString(R.string.scene_afternoon))) {//"下午"
            mGroup.setSw(127);
            mGroup.setLd1(118);
            mGroup.setMode(2);
            mSceneIndex = 4;
            AppManager.getInstance(mainActivity).controlScene(mGroup, "7f7f0000", "7f7fff");

        } else if (name.equalsIgnoreCase(getString(R.string.scene_moonlight))) {//"月光"
            mGroup.setSw(0);
            mGroup.setLd1(118);
            mGroup.setMode(2);
            mSceneIndex = 5;
            AppManager.getInstance(mainActivity).controlScene(mGroup, "00ff0000", "7f7fff");

        } else if (name.equalsIgnoreCase(getString(R.string.scene_auxiliary))) {//"辅助灯"
            boolean isOn = SPUtil.getBool(Constants.ISON, false);
            mSceneIndex = 6;
            mGroup.setMode(2);
            int seed = mCurrFamily.getSeed();
            int feedback = mCurrFamily.getFeedback();
            if (mGroup.getFamilyId().equalsIgnoreCase("12345678")) {
                seed = 73;
                feedback = 4777;
            }
            if (isOn) {
                AppManager.getInstance(mainActivity).commandSceneCmd("01", mGroup.getFamilyId(), mGroup.getGroupId(), "00000000", "000000", seed, feedback);
                isOn = false;
            } else {
                AppManager.getInstance(mainActivity).commandSceneCmd("01", mGroup.getFamilyId(), mGroup.getGroupId(), "00000000", "000100", seed, feedback);
                isOn = true;
            }
            SPUtil.put(Constants.ISON, isOn);

        } else if (name.equalsIgnoreCase(getString(R.string.scene_auxiliary))) {//"分段"
            mSceneIndex = 7;
            mGroup.setMode(2);
            int seed2 = mCurrFamily.getSeed();
            int feedback2 = mCurrFamily.getFeedback();
            if (mGroup.getFamilyId().equalsIgnoreCase("12345678")) {
                seed2 = 73;
                feedback2 = 4777;
            }
            AppManager.getInstance(mainActivity).commandCmd("08", mGroup.getFamilyId(), mGroup.getGroupId(), "00000000", "000000", seed2, feedback2);
        }
        resetSeekBarValue();
        setCurrScene();
        isControlScene = false;
    }


    @Override
    public void onPause() {
        super.onPause();
        isOnResume = false;
    }

    private void setCurrScene() {
        List<Scene> sceneModes = mSceneModeAdapter.getAllData();
        if (sceneModes == null || sceneModes.size() < 1) {
            sceneModes = null;
            return;
        } else {
            for (Scene sceneMode : sceneModes) {
                sceneMode.setChecked(false);
            }
            if (mSceneIndex < 0 || mSceneIndex >= sceneModes.size()) mSceneIndex = 0;
            mScene = sceneModes.get(mSceneIndex);
            mScene.setChecked(true);
            mSceneModeAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mColorPicker != null) {
            mColorPicker.destroyBitmap();
            mColorPicker = null;
        }
       /* if (AppManager.getInstance(getContext()).mAllGroup != null) {
            AppManager.getInstance(getContext()).mAllGroup = null;
        } */

        if (AppManager.getInstance(getContext()).isControlAll) {
            AppManager.getInstance(getContext()).isControlAll = false;
        }
        mSWSceneList.clear();
        mSWSceneList = null;
        mRGBSceneList.clear();
        mRGBSceneList = null;
        mGroup = null;
        mScene = null;

    }

    @Override
    protected void confirmOperation() {
        super.confirmOperation();
        if (confirmType == 1) {//设置组
            AppManager.getInstance(mainActivity).notifyAddGroup(mGroup);
        }
    }

}
